package com.itheima.project.handler.wechat.config;

import com.itheima.project.constant.trade.TradingConstant;
import com.itheima.project.core.enums.trade.TradingEnum;
import com.itheima.project.exception.ProjectException;
import com.itheima.project.face.PayChannelFace;
import com.itheima.project.handler.wechat.client.Config;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.vo.basic.OtherConfigVo;
import com.itheima.project.vo.trade.PayChannelVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName WeChatPayConfig.java
 * @Description 微信配置类
 */
@Configuration
public class WechatPayConfig {

    @Autowired
    PayChannelFace payChannelFace;


    @Async
    @PostConstruct
    public void initConfig(){
        Timer timer = new Timer();
        timer.schedule(new InitTask(timer),10*1000);
    }

    class InitTask extends TimerTask {

        private Timer timer;

        private InitTask(Timer timer) {
            this.timer= timer;
        }

        @Override
        public void run() {
            //初始化阿里云SMS的配置信息
            payChannelFace.findPayChannelList(TradingConstant.TRADING_CHANNEL_WECHAT_PAY);
        }
    }

    /***
     * @description 获得配置
     * @return
     */
    public Config queryConfig(Long enterpriseId){
        //1、缓存配置
        List<PayChannelVo> payChannelVos = payChannelFace.findPayChannelList(TradingConstant.TRADING_CHANNEL_WECHAT_PAY);
        if (EmptyUtil.isNullOrEmpty(payChannelVos)){
            throw  new ProjectException(TradingEnum.CONFIG_EMPT);
        }
        List<PayChannelVo> payChannelVoRestult = payChannelVos.stream()
                .filter(n -> n.getEnterpriseId().longValue() == enterpriseId.longValue())
                .collect(Collectors.toList());
        //2、配置信息校验
        if (EmptyUtil.isNullOrEmpty(payChannelVoRestult)&&payChannelVoRestult.size()>1){
            throw  new ProjectException(TradingEnum.CONFIG_ERROR);
        }
        PayChannelVo payChannelVo = payChannelVoRestult.get(0);
        //2、转换其他属性为map结构
        List<OtherConfigVo> otherConfigs = payChannelVo.getOtherConfigs();
        Map<String,String> otherConfigMap = new HashMap<>();
        otherConfigs.forEach(n->{
            otherConfigMap.put(n.getConfigKey(),n.getConfigValue());
        });
        return Config.builder()
                .appid(payChannelVo.getAppId())
                .domain(payChannelVo.getDomain())
                .mchId(otherConfigMap.get("mchId"))
                .mchSerialNo(otherConfigMap.get("mchSerialNo"))
                .apiV3Key(otherConfigMap.get("apiV3Key"))
                .privateKey(payChannelVo.getMerchantPrivateKey())
                .notifyUrl(payChannelVo.getNotifyUrl())
                .build();
    }
}
